import logging

from flask import jsonify
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from flask_wtf.csrf import generate_csrf

from info import create_app, db, models

# 创建 app，并传入配置模式：development / production
from info.models import User
from info.utils.response_code import RET

app = create_app("development")


# 添加钩子函数，每次请求结束时，向cookie中添加csrf_stoken
@app.after_request
def after_request(response):
    # 生成csrf_token
    csrf_token = generate_csrf()
    # 设置cookie
    response.set_cookie("csrf_token", csrf_token)
    return response


@app.teardown_request
def teardown_request(e):
    # 数据库操作失败时，回滚
    if e:
        app.logger.error(e)
        db.session.rollback()
    else:
        db.session.commit()


# flask_script 方式运行
manager = Manager(app)
Migrate(app, db)
# 将数据库迁移添加到falsk_script中，命令为"db"
manager.add_command("db", MigrateCommand)


# 创建管理员用户
@manager.option("-n", "-name", dest="name")
@manager.option("-p", "-password", dest="password")
def create_admin(name, password):
    if not all([name, password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    user = User()
    user.mobile = name
    user.nick_name = name
    user.password = password
    user.is_admin = True
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据存储错误")
    return jsonify(errno=RET.OK, errmsg="添加成功")


if __name__ == '__main__':
    print(app.url_map)
    manager.run()
